import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QColor, QBrush, QIcon
from PyQt5.QtCore import QTimer
from dialog import *
import sys
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu, QAction



class MyMainForm(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainForm, self).__init__(parent)
        self.setupUi(self)
        self.hvSetDialog=hvSetDialog(self)
        self.hvSetDialog.set_callback(self.handleUdpInput)
        self.getTelePerSec = QTimer(self)
        self.getTelePerSec.timeout.connect(self.getTelePerSec_func)
        self.getTelePerSec.start(1000)
        self.cxpd_can_ins=cxpd_can()
        self.Table_teleShow.setEditTriggers(QTableWidget.NoEditTriggers)
        self.tele_data_buf=[[0]*31,0*31]
        self.cmd_queue=[]
        self.log_file=open(f"./log_{time.strftime("%Y%m%d%H%M%S", time.localtime())}.txt","w+")

        self.Btn_fetchUdpData.clicked.connect(self.open_UdpTrans)
        self.Btn_updataFirm.clicked.connect(self.open_Ota)
        self.Btn_singleCmd.clicked.connect(self.singleCmd)
        self.Btn_hvSet.clicked.connect(self.open_hvSet)
        self.Btn_dacStart.clicked.connect(self.open_dacSet)
        self.Btn_tmlStart.clicked.connect(self.open_tmlSet)
        self.Btn_tmlDataEn.clicked.connect(self.open_enTmlData)
        self.Btn_monDataEn.clicked.connect(self.open_enMonData)
        self.Btn_ShutDown.clicked.connect(self.open_shutDown)
        self.Btn_compress.clicked.connect(self.open_compressSet)
        self.Btn_testData.clicked.connect(self.start_testData)
        self.Btn_hvSdata.clicked.connect(self.start_hvSdata)
        self.Btn_hvProtectCfg.clicked.connect(self.open_hvProtectSet)
        self.Btn_claLog.clicked.connect(self.cla_log)
        self.Btn_canRecon.clicked.connect(self.can_reConnect)
        self.comboBox_hvModuleSel.addItems(hv_module_dic.keys())
        self.comboBox_hvModuleSel.currentIndexChanged.connect(self.hvModChange)

    
    def can_reConnect(self):
        if(self.cxpd_can_ins.can_start()):
            self.append_log("CAN启动成功")
        else:
            self.append_log("CAN启动失败")
    
    def getTelePerSec_func(self):
        self.cxpd_can_ins.utc_pos()
        if(len(self.cmd_queue)>0):
            cmd_str=self.cmd_queue.pop(0)
            self.append_log(f'发送指令： {cmd_str}')
            self.cxpd_can_ins.cxpd_cmd_str(cmd_str)
        temp_buf = self.cxpd_can_ins.cxpd02_mon_get(debug=False)
        self.lcdNumber_cmdLeave.display(len(self.cmd_queue))
        if(temp_buf):
            self.tele_data_buf = temp_buf
            for row in range(30):
                item = QTableWidgetItem(f"{self.tele_data_buf[0][row]}")
                self.Table_teleShow.setItem(row, 0, item)
                item = QTableWidgetItem(hex(self.tele_data_buf[1][row]))
                self.Table_teleShow.setItem(row, 1, item)
        else:
            self.append_log(f'遥测请求失败!')

    def hvModChange(self):
        self.cxpd_can_ins.hv_module_type=self.comboBox_hvModuleSel.currentText()
        self.append_log(f"设置当前高压模块为{self.cxpd_can_ins.hv_module_type}, 最高输出电压为-{hv_module_dic[self.cxpd_can_ins.hv_module_type][0]}V, 最大输出电流为{hv_module_dic[self.cxpd_can_ins.hv_module_type][1]}uA")

    
    def open_UdpTrans(self):
        self.udpDialog = UdpDialog(self)
        self.udpDialog.set_callback(self.handleUdpInput)
        self.udpDialog.show()
    
    def open_hvSet(self):
        hv_mod_param=hv_module_dic[self.cxpd_can_ins.hv_module_type]
        self.hvSetDialog=hvSetDialog(self,self.hvSetDialog.last_set,hv_mod_param[0],hv_mod_param[1])
        self.hvSetDialog.label_warning.setText(f"注意!当前设置高压模块为{self.cxpd_can_ins.hv_module_type}\n-{hv_mod_param[0]}V,{hv_mod_param[1]}uA, 请确认！")
        self.hvSetDialog.set_callback(self.handleUdpInput)
        self.hvSetDialog.show()
    
    def open_Ota(self):
        self.otaDialog=OtaDialog(self)
        self.otaDialog.set_callback(self.handleUdpInput)
        self.otaDialog.show()
    
    def open_dacSet(self):
        self.dacSetDialog=startSetDialog(self,startBias_dict)
        self.dacSetDialog.set_callback(self.handleUdpInput,set_vol_mv,accept_precmd=dac8568_init)
        self.dacSetDialog.show()

    def open_tmlSet(self):
        self.tmlSetDialog=startSetDialog(self,startTML_dict)
        self.tmlSetDialog.set_callback(self.handleUdpInput,set_tml)
        self.tmlSetDialog.show()
    
    
    def open_hvProtectSet(self):
        self.tmlSetDialog=startSetDialog_withParam(self,start_hvProtect)
        self.tmlSetDialog.set_callback(self.handleUdpInput,set_hvProtect,append_param=self.cxpd_can_ins.hv_module_type)
        self.tmlSetDialog.show()

    def open_compressSet(self):
        self.tmlSetDialog=startSetDialog(self,startCompressdict)
        self.tmlSetDialog.set_callback(self.handleUdpInput,set_addrNum)
        self.tmlSetDialog.show()

    def open_enTmlData(self):
        self.tmlSetDialog=enSetDialog(self,tml_data_enSet)
        self.tmlSetDialog.label.setText("协处理器数据使能")
        self.tmlSetDialog.set_callback(self.handleUdpInput)
        self.tmlSetDialog.show()

    def open_enMonData(self):
        self.tmlSetDialog=enSetDialog(self,mon_data_enSet)
        self.tmlSetDialog.label.setText("监控数据使能")
        self.tmlSetDialog.set_callback(self.handleUdpInput)
        self.tmlSetDialog.show()

    def open_shutDown(self):
        self.tmlSetDialog=oneCmdDialog(self,shutdownlist)
        self.tmlSetDialog.label.setText("预调电指令：\n发送以后停止取数，存储emmc地址，\n关闭高压，关闭DAC\n掉电前2分钟发送\n确认是否发送？")
        self.tmlSetDialog.set_callback(self.handleUdpInput)
        self.tmlSetDialog.show()
    
    

    
    def start_testData(self):
        num_str=self.lineEdit_testData.text()
        num=try_trans_uint(num_str)
        if(num==None):
            self.append_log("输入错误！")
            return
        if(num>0xffffffff):
            self.append_log("输入超过最大限制，默认设置为 0xffffffff.")
            num=0xffffffff
        cmd_str="05ff0000"+hex(num)[2:].rjust(8,'0')
        self.cmd_queue.append(cmd_str)
    
    def start_hvSdata(self):
        num_str=self.lineEdit_hvSdata.text()
        num=try_trans_uint(num_str)
        if(num==None):
            self.append_log("输入错误！")
            return
        if(num>0xffffffff):
            self.append_log("输入超过最大限制，默认设置为 0xffffffff.")
            num=0xffffffff
        cmd_str="05a20000"+hex(num)[2:].rjust(8,'0')
        self.cmd_queue.append(cmd_str)

    def start_thrSet(self):
        num_str=self.lineEdit_thrSet.text()
        num_str8,num=try_trans_signedHex(num_str)
        if(num_str8==None):
            self.append_log("输入错误！")
            return
        if(num>2047 or num<-2048):
            self.append_log("输入超过限制(-2048,2047)")
            return
        cmd_str="05100000"+num_str8
        self.cmd_queue.append(cmd_str)


    def handleUdpInput(self, cmd_ls:list):
        # 处理从对话框接收到的输入
        for cmd_str in cmd_ls:
            self.cmd_queue.append(cmd_str)
    
    def append_log(self,log_text):
        time_step=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.textBrowser_logPrint.append(time_step+': '+log_text+'\n')
        self.log_file.write(time_step+': '+log_text+'\n')
    
    def cla_log(self):
        self.textBrowser_logPrint.clear()
    
    def singleCmd(self):
        try:
            cmd_str=self.lineEdit_singleCmd.text()
            cmd_str=cmd_str.replace('_','').replace(' ','')
            print(cmd_str)
            if(len(cmd_str)==16):
                bytes.fromhex(cmd_str)
                self.cmd_queue.append(cmd_str)
        except:
            return

        

if __name__ == "__main__":
    app = QApplication(sys.argv)
    MainWindow = MyMainForm()
    icon = QtGui.QIcon('./cxpd02.png')
    MainWindow.setWindowIcon(icon)
    MainWindow.setWindowTitle('CXPD02上位机')
    MainWindow.show()
    sys.exit(app.exec_())
